package site.syksy.qingzhou.upms.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import site.syksy.qingzhou.common.properties.QingZhouProperties;
import site.syksy.qingzhou.upms.domain.RouteDO;
import site.syksy.qingzhou.upms.mapper.RouteMapper;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Raspberry
 */
@Service
public class ApiService {

    @Autowired
    RouteMapper routeMapper;

    @Resource
    QingZhouProperties qingZhouProperties;

    private static final String ROLE = "QZ_ROLE";

    /**
     * 获取全部在线的接口路由,并且校验类型为登录和授权
     *
     * @return
     */
    public Map<String, List<ConfigAttribute>> selectAll() {
        QueryWrapper<RouteDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RouteDO::getOnline, true);
        List<RouteDO> routeDOList = routeMapper.selectList(queryWrapper);

        AntPathMatcher matcher = new AntPathMatcher();
        Map<String, List<ConfigAttribute>> methodMap = new HashMap<>();
        for (RouteDO routeDO : routeDOList) {
            if (!webIgnoringAntMatchers(matcher, routeDO.getPattern())) {
                String handlerMethod = routeDO.getHandlerMethod();
                handlerMethod = handlerMethod.replace("#", ".");
                int leftParenthesisIndex = handlerMethod.indexOf("(");
                handlerMethod = handlerMethod.substring(0, leftParenthesisIndex);
                methodMap.put(handlerMethod, SecurityConfig.createList(ROLE));

            }
        }
        return methodMap;
    }

    /**
     * 全局免登录配置匹配
     *
     * @param matcher
     * @param pattern
     * @return
     */
    public boolean webIgnoringAntMatchers(AntPathMatcher matcher, String pattern) {
        QingZhouProperties.Security security = qingZhouProperties.getSecurity();
        if (security != null) {
            Set<String> webIgnoringSet = security.getWebIgnoring();
            for (String webIgnoring : webIgnoringSet) {
                if (matcher.match(webIgnoring, pattern)) {
                    return true;
                }
            }
        }
        return false;
    }
}
